package ru.evga.inse.core.service.dict.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ru.evga.inse.core.dao.DaoException;
import ru.evga.inse.core.dao.IDao;
import ru.evga.inse.core.dao.IResultContainer;
import ru.evga.inse.core.dao.dict.ICityDao;
import ru.evga.inse.core.dao.dict.IStreetDao;
import ru.evga.inse.core.domain.dict.City;
import ru.evga.inse.core.domain.dict.Street;
import ru.evga.inse.core.filter.dict.StreetFilter;
import ru.evga.inse.core.service.dict.IStreetService;
import ru.evga.inse.core.service.impl.GenericEntityService;


@Service
@Configurable
public class StreetService
    extends GenericEntityService<Street>
    implements IStreetService
{
    @Autowired
    private IStreetDao m_streetDao;
    @Autowired
    private ICityDao m_cityDao;

    @Override
    protected IDao<Long, Street> getDao()
    {
        return m_streetDao;
    }
    
    @Transactional
    public Street save(Long id, String name, City city)
        throws DaoException
    {
//        City cityReference = m_cityDao.getReference(city);
        //TODO replace to getReference (���� ���������� ������ ��������� � ������� �� city)
        City cityReference = m_cityDao.find(city == null ? null : city.getId());
        if(id != null)
        {
            Street existStreet = m_streetDao.find(id);
            existStreet.setName(name);
            existStreet.setCity(cityReference);
            return m_streetDao.merge(existStreet);
        }
        
        Street street = new Street();
        street.setName(name);
        street.setCity(cityReference);
        return m_streetDao.persist(street);
    }
    
    public IResultContainer<Street> findRange(Integer firstResult, Integer maxResults,
        String orderBy, Boolean isAsc, StreetFilter filter)
        throws DaoException
    {
        return m_streetDao.findRange(firstResult, maxResults, orderBy, isAsc, filter);
    }
}
